package cn.bby.jtk.web;

import cn.bby.jtk.base.constant.CommonErrorCode;
import cn.bby.jtk.base.exception.ServiceException;
import lombok.Data;

import java.io.Serializable;

/**
 * @author ben
 * @since 2025/4/12 02:38
 */
@Data
public class CommonResult<T> implements Serializable {
    private static final long serialVersionUID = 4234796760958866086L;
    /**
     * 错误码，前端可以据此提示
     */
    private String code;
    /**
     * 成功时为实体信息
     */
    private T data;
    /**
     * 错误时的描述
     */
    private String msg;

    public CommonResult() {
        code = CommonErrorCode.SUCCESS;
    }

    public CommonResult(T data) {
        this.data = data;
        this.code = CommonErrorCode.SUCCESS;
    }

    public CommonResult(ServiceException e) {
        this.code = e.getCode();
        this.msg = e.getMessage();
    }

    public CommonResult(String code, T data) {
        this.code = code;
        this.data = data;
    }

    public CommonResult(String code, String msg) {
        this.code = code;
        this.msg = msg;
    }

    public static <R> CommonResult<R> success() {
        return new CommonResult<>();
    }

    public static <R> CommonResult<R> success(R data) {
        return new CommonResult<>(data);
    }

    public static <R> CommonResult<R> error(String code, String msg) {
        return new CommonResult<>(code, msg);
    }
    public static <R> CommonResult<R> error(String code, R data) {
        return new CommonResult<>(code, data);
    }
}
